<template>
  <div class="user-goods-page">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="nav-container">
        <h1 class="logo">商城</h1>
        <div class="user-info">
          <span>欢迎，{{ userInfo.username }}</span>
          <el-button type="text" @click="logout">退出登录</el-button>
        </div>
      </div>
    </div>

    <div class="main-container">
      <!-- 左侧商品类型导航 -->
      <div class="sidebar">
        <div class="category-title">商品分类</div>
        <div class="category-list">
          <div 
            class="category-item" 
            :class="{ active: selectedTypeId === null }"
            @click="selectCategory(null)"
          >
            <el-icon><Grid /></el-icon>
            <span>全部商品</span>
          </div>
          <div 
            v-for="type in typeList" 
            :key="type.id"
            class="category-item"
            :class="{ active: selectedTypeId === type.id }"
            @click="selectCategory(type.id)"
          >
            <el-icon><Box /></el-icon>
            <span>{{ type.name }}</span>
          </div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-area">
        <!-- 商品展示区域 -->
        <div class="goods-section">
          <!-- 秒杀商品区域 -->
          <div class="seckill-section" v-if="seckillGoods.length > 0">
            <div class="section-header">
              <h2><el-icon><Clock /></el-icon>限时秒杀</h2>
              <div class="countdown">距离结束：{{ countdown }}</div>
            </div>
            <div class="goods-grid seckill-grid">
              <div 
                v-for="goods in seckillGoods" 
                :key="goods.id"
                class="goods-card seckill-card"
              >
                <div class="goods-image">
                  <img :src="goods.image || '/default-goods.jpg'" :alt="goods.name" />
                  <div class="seckill-badge">秒杀</div>
                </div>
                <div class="goods-info">
                  <h3 class="goods-name">{{ goods.name }}</h3>
                  <p class="goods-desc">{{ goods.description }}</p>
                  <div class="price-info">
                    <span class="seckill-price">¥{{ goods.seckillPrice }}</span>
                    <span class="original-price">¥{{ goods.price }}</span>
                  </div>
                  <div class="stock-info">
                    <span>库存：{{ goods.stock }}</span>
                    <span>已售：{{ goods.sales }}</span>
                  </div>
                  <el-button type="danger" class="buy-btn" @click="buySeckill(goods)">立即抢购</el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 普通商品区域 -->
          <div class="normal-section">
            <div class="section-header">
              <h2><el-icon><ShoppingBag /></el-icon>{{ selectedTypeName || '全部商品' }}</h2>
              <div class="sort-options">
                <el-select v-model="sortBy" @change="handleSort" placeholder="排序方式">
                  <el-option label="默认排序" value="default"></el-option>
                  <el-option label="价格从低到高" value="price_asc"></el-option>
                  <el-option label="价格从高到低" value="price_desc"></el-option>
                  <el-option label="销量从高到低" value="sales_desc"></el-option>
                </el-select>
              </div>
            </div>
            <div class="goods-grid">
              <div 
                v-for="goods in normalGoods" 
                :key="goods.id"
                class="goods-card"
              >
                <div class="goods-image">
                  <img :src="goods.image || '/default-goods.jpg'" :alt="goods.name" />
                </div>
                <div class="goods-info">
                  <h3 class="goods-name">{{ goods.name }}</h3>
                  <p class="goods-desc">{{ goods.description }}</p>
                  <div class="price-info">
                    <span class="current-price">¥{{ goods.price }}</span>
                  </div>
                  <div class="stock-info">
                    <span>库存：{{ goods.stock }}</span>
                    <span>已售：{{ goods.sales }}</span>
                  </div>
                  <el-button type="primary" class="buy-btn" @click="buyGoods(goods)">立即购买</el-button>
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[12, 24, 36, 48]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>

        <!-- 个人地址管理区域 -->
        <div class="address-section">
          <div class="section-header">
            <h2><el-icon><Location /></el-icon>我的地址</h2>
            <el-button type="primary" size="small" @click="showAddAddress">添加地址</el-button>
          </div>
          <div class="address-list">
            <div 
              v-for="address in addressList" 
              :key="address.id"
              class="address-card"
              :class="{ default: address.isdefault === 1 }"
            >
              <div class="address-info">
                <div class="address-header">
                  <span class="receiver">{{ address.receiver }}</span>
                  <span class="phone">{{ address.phone }}</span>
                  <el-tag v-if="address.isdefault === 1" type="success" size="small">默认</el-tag>
                </div>
                <div class="address-detail">
                  {{ address.province }} {{ address.city }} {{ address.area }} {{ address.detail }}
                </div>
              </div>
              <div class="address-actions">
                <el-button type="text" size="small" @click="editAddress(address)">编辑</el-button>
                <el-button type="text" size="small" @click="setDefaultAddress(address)" v-if="address.isdefault !== 1">设为默认</el-button>
                <el-button type="text" size="small" @click="deleteAddress(address)" style="color: #f56c6c;">删除</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 地址管理弹窗 -->
    <el-dialog v-model="addressDialogVisible" :title="addressDialogTitle" width="500px">
      <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="80px">
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="addressForm.receiver" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input v-model="addressForm.province" placeholder="请输入省份" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="addressForm.city" placeholder="请输入城市" />
        </el-form-item>
        <el-form-item label="区域" prop="area">
          <el-input v-model="addressForm.area" placeholder="请输入区域" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="addressForm.detail" type="textarea" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isdefault" :true-label="1" :false-label="0">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Grid, Box, Clock, ShoppingBag, Location } from '@element-plus/icons-vue'
import goodsApi from '../api/goodsApi.js'
import typeApi from '../api/typeApi.js'
import addressApi from '../api/addressApi.js'
import { useRouter } from 'vue-router'

const router = useRouter()

// 用户信息
const userInfo = ref({
  username: localStorage.getItem('username') || '用户'
})

// 商品类型相关
const typeList = ref([])
const selectedTypeId = ref(null)
const selectedTypeName = computed(() => {
  if (!selectedTypeId.value) return '全部商品'
  const type = typeList.value.find(t => t.id === selectedTypeId.value)
  return type ? type.name : '全部商品'
})

// 商品数据
const normalGoods = ref([])
const seckillGoods = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const sortBy = ref('default')

// 地址管理相关
const addressList = ref([])
const addressDialogVisible = ref(false)
const addressDialogTitle = ref('添加地址')
const addressForm = ref({
  receiver: '',
  phone: '',
  province: '',
  city: '',
  area: '',
  detail: '',
  isdefault: 0
})
const addressFormRef = ref()

// 表单验证规则
const addressRules = {
  receiver: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
  city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
  area: [{ required: true, message: '请输入区域', trigger: 'blur' }],
  detail: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

// 秒杀倒计时
const countdown = ref('23:59:59')

// 获取商品类型列表
const getTypeList = async () => {
  try {
    const result = await typeApi.list()
    typeList.value = result
  } catch (error) {
    console.error('获取商品类型失败:', error)
  }
}

// 获取商品列表
const getGoodsList = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      typeid: selectedTypeId.value || '',
      status: 1, // 只显示上架商品
      isdel: 0
    }
    
    const result = await goodsApi.page(params)
    if (result && result.records) {
      let goods = result.records
      
      // 排序处理
      if (sortBy.value === 'price_asc') {
        goods.sort((a, b) => a.price - b.price)
      } else if (sortBy.value === 'price_desc') {
        goods.sort((a, b) => b.price - a.price)
      } else if (sortBy.value === 'sales_desc') {
        goods.sort((a, b) => b.sales - a.sales)
      }
      
      // 暂时将所有商品都作为普通商品显示
      // 后续可以根据实际需求添加秒杀商品的标识字段
      seckillGoods.value = []
      normalGoods.value = goods
      
      total.value = result.total || 0
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败')
    console.error('获取商品列表失败:', error)
  }
}

// 获取地址列表
const getAddressList = async () => {
  try {
    const result = await addressApi.page({ page: 1, pageSize: 100, isdel: 0 })
    if (result && result.records) {
      addressList.value = result.records
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
  }
}

// 选择商品类型
const selectCategory = (typeId) => {
  selectedTypeId.value = typeId
  currentPage.value = 1
  getGoodsList()
}

// 排序处理
const handleSort = () => {
  getGoodsList()
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  getGoodsList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  getGoodsList()
}

// 购买商品
const buyGoods = (goods) => {
  ElMessage.success(`准备购买：${goods.name}`)
  // 这里可以跳转到购买页面或打开购买弹窗
}

// 秒杀商品
const buySeckill = (goods) => {
  ElMessage.success(`准备抢购：${goods.name}`)
  // 这里可以跳转到秒杀页面或打开秒杀弹窗
}

// 显示添加地址弹窗
const showAddAddress = () => {
  addressDialogTitle.value = '添加地址'
  addressForm.value = {
    receiver: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    detail: '',
    isdefault: 0
  }
  addressDialogVisible.value = true
}

// 编辑地址
const editAddress = (address) => {
  addressDialogTitle.value = '编辑地址'
  addressForm.value = { ...address }
  addressDialogVisible.value = true
}

// 保存地址
const saveAddress = async () => {
  try {
    await addressFormRef.value.validate()
    
    if (addressForm.value.id) {
      await addressApi.update(addressForm.value)
      ElMessage.success('地址更新成功')
    } else {
      await addressApi.add(addressForm.value)
      ElMessage.success('地址添加成功')
    }
    
    addressDialogVisible.value = false
    getAddressList()
  } catch (error) {
    console.error('保存地址失败:', error)
  }
}

// 设为默认地址
const setDefaultAddress = async (address) => {
  try {
    await addressApi.update({ ...address, isdefault: 1 })
    ElMessage.success('设置默认地址成功')
    getAddressList()
  } catch (error) {
    ElMessage.error('设置默认地址失败')
  }
}

// 删除地址
const deleteAddress = async (address) => {
  try {
    await ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await addressApi.delete(address.id)
    ElMessage.success('地址删除成功')
    getAddressList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除地址失败')
    }
  }
}

// 退出登录
const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('username')
  router.push('/login')
}

// 秒杀倒计时更新
const updateCountdown = () => {
  const now = new Date()
  const tomorrow = new Date(now)
  tomorrow.setDate(tomorrow.getDate() + 1)
  tomorrow.setHours(0, 0, 0, 0)
  
  const diff = tomorrow - now
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((diff % (1000 * 60)) / 1000)
  
  countdown.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 页面初始化
onMounted(() => {
  getTypeList()
  getGoodsList()
  getAddressList()
  
  // 启动倒计时
  updateCountdown()
  setInterval(updateCountdown, 1000)
})
</script>

<style scoped>
.user-goods-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.top-nav {
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.main-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  display: flex;
  gap: 20px;
}

.sidebar {
  width: 200px;
  background: white;
  border-radius: 8px;
  padding: 20px;
  height: fit-content;
  position: sticky;
  top: 100px;
}

.category-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s;
  margin-bottom: 5px;
}

.category-item:hover {
  background-color: #f0f9ff;
  color: #409eff;
}

.category-item.active {
  background-color: #409eff;
  color: white;
}

.content-area {
  flex: 1;
}

.goods-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-header h2 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 18px;
}

.countdown {
  color: #f56c6c;
  font-weight: bold;
}

.sort-options {
  width: 150px;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.seckill-grid {
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.goods-card {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  background: white;
}

.goods-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  transform: translateY(-2px);
}

.seckill-card {
  border-color: #f56c6c;
}

.goods-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.seckill-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  background: #f56c6c;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.goods-info {
  padding: 15px;
}

.goods-name {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 8px 0;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-desc {
  color: #666;
  font-size: 14px;
  margin: 0 0 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.price-info {
  margin-bottom: 10px;
}

.current-price, .seckill-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.original-price {
  color: #999;
  font-size: 14px;
  text-decoration: line-through;
  margin-left: 8px;
}

.stock-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 15px;
}

.buy-btn {
  width: 100%;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.address-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.address-list {
  display: grid;
  gap: 15px;
}

.address-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.address-card.default {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.address-info {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.receiver {
  font-weight: bold;
  color: #333;
}

.phone {
  color: #666;
}

.address-detail {
  color: #666;
  font-size: 14px;
}

.address-actions {
  display: flex;
  gap: 10px;
}

.seckill-section {
  margin-bottom: 30px;
}

.normal-section {
  margin-top: 20px;
}
</style>